package com.klb.base;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.klb.tools.Tools;

/**
 * Created by fujia on 2016/6/7.
 */
public abstract class DaoBase {
    protected SessionFactory hibernateSessionFactory;

    public void setHibernateSessionFactory(SessionFactory HibernateSessionFactory) {
        hibernateSessionFactory = HibernateSessionFactory;
    }


    /**
     * 增加记录
     * */
    public boolean addQuery(Object object){
        if (!Tools.objectIsNullOrNot(object)){
            Session session = this.hibernateSessionFactory.getCurrentSession();
            Transaction tx = null;

            try {
                tx = session.beginTransaction();
                session.save(object);
                tx.commit();
                return true;
            }catch (Exception e){
                tx.rollback();
                e.printStackTrace();
            }
        }

        return false;
    }


    /**
     * 修改记录
     * */
    public boolean editQuery(Object object){
        if (!Tools.objectIsNullOrNot(object)){
            Session session = this.hibernateSessionFactory.getCurrentSession();
            Transaction tx = null;

            try {
                tx = session.beginTransaction();
                session.saveOrUpdate(object);
                tx.commit();
                return true;
            }catch (Exception e){
                tx.rollback();
                e.printStackTrace();
            }
        }

        return false;
    }


    /**
     * 删除记录
     * */
    public boolean deleteQuery(Object object){
        if (!Tools.objectIsNullOrNot(object)){
            Session session = this.hibernateSessionFactory.getCurrentSession();
            Transaction tx = null;

            try {
                tx = session.beginTransaction();
                session.delete(object);
                tx.commit();
                return true;
            }catch (Exception e){
                tx.rollback();
                e.printStackTrace();
            }
        }

        return false;
    }


}
